const fs = require('fs')
const path = require('path')
const program = require('commander')
const glob = require('glob')
const superagent = require('superagent')
const { resolve, prefix, getToken, isPc } = require('./utils')

module.exports = async () => {
  const token = getToken()
  if (!token) return

  const files = glob.sync(resolve('src/admins/**/property.json'))
    .concat(glob.sync(resolve('src/components/**/property.json')))

  const projDir = resolve()

  const queue = files.map(file => {
    return new Promise((reslove, reject) => {
      fs.readFile(file, (err, data) => {
        if (err) reject(err)
        reslove({
          path: path.relative(projDir, file),
          content: data.toString()
        })
      })
    })
  })

  const filesData = await Promise.all(queue)

  console.info('开始提交文件,请稍后...')

  const res = await superagent
    .post('/GitFile/Admin', {
      loginInput: token,
      codeType: isPc ? 2 : 1,
      files: filesData.filter(data => data.content)
    })
    .use(prefix)

  const { result, status, message } = res.body

  if (status !== 1) {
    console.log('校验错误', message)
    return
  }

  result.forEach((file) => {
    fs.writeFile(resolve(file.path), file.content, err => {
      if (err) {
        if (program.debug) console.error(err)
        console.log(`配置更新失败，路径 ${file.path}`)
        return
      }
      console.log(`配置更新成功，路径 ${file.path}`)
    })
  })
}
